﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace YourFileWatcher.Services
{
    /// <summary>
    /// 将对象保存为文件的逻辑
    /// </summary>
    public class SerializeFileService
    {
        /// <summary>
        /// 以 XML 文件格式序列化保存
        /// </summary>
        /// <param name="pFilePath">保存文件路径</param>
        /// <param name="pObject">要保存的对象</param>
        public void SerializeXml(string pFilePath, object pObject)
        {
            using (var sr = new FileStream(pFilePath, FileMode.Create, FileAccess.Write))
            {
                XmlSerializer serializer = new XmlSerializer(pObject.GetType());
                serializer.Serialize(sr, pObject);
            }
        }

        /// <summary>
        /// 以 二进制 文件格式序列化保存
        /// </summary>
        /// <param name="pFilePath">保存文件路径</param>
        /// <param name="pObject">要保存的对象</param>
        public void SerializeBinary(string pFilePath, object pObject)
        {
            using (Stream stream = new FileStream(pFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, pObject);
            }
        }

        /// <summary>
        /// 将 二进制 文件格式反序列化为对象
        /// </summary>
        /// <param name="pFilePath">保存文件路径</param>
        /// <typeparam name="T">类型T：反序列化后转化的对象类型</typeparam>
        public T DeserializeBinary<T>(string pFilePath)
        {
            using (Stream stream = new FileStream(pFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                IFormatter formatter = new BinaryFormatter();
                T result = (T)formatter.Deserialize(stream);
                return result;
            }
        }
    }
}
